﻿using System;
using System.Collections.Generic;
using System.Data.SQLite;
using System.Linq;
using System.Windows.Forms;
using Sunlight.Dispatch.Dal;
using Sunlight.Dispatch.Model;
using Sunlight.Dispatch.Tools;
using Sunlight.Dispatch.UI.Controls;
using Sunlight.Dispatch.UI.Extensions;

namespace Sunlight.Dispatch.UI {
    public partial class TSideOperationFrm : BaseFrm {
        private readonly List<TSideList> sideLists = new List<TSideList>();
        public TSideOperationFrm() {
            InitializeComponent();
            this.Load += TSideOperationFrm_Load;
        }

        private void TSideOperationFrm_Load(object sender, EventArgs e) {
            this.Register.RegisterNumber(new[] { this.txbTimeoutMinute });

            this.dataGridView1.AllowUserToAddRows = false;
            this.dataGridView1.AllowUserToDeleteRows = true;
            this.dataGridView1.AutoGenerateColumns = false;
            this.dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            this.dataGridView1.AllowUserToAddRows = false;
            this.dataGridView1.AllowUserToAddRows = false;

            this.dataGridView1.Columns[0].ContextMenuStrip = this.contextMenuStrip;
            this.sideLists.Clear();
            dataGridView1.Columns[0].MinimumWidth = 20;
            dataGridView1.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
            dataGridView1.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
            dataGridView1.Columns[2].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;

            dataGridView1.ScrollBars = ScrollBars.Horizontal;
            dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            dataGridView1.SelectionChanged += this.DataGridView_SelectionChanged;
            dataGridView1.MultiSelect = false;
            dataGridView1.RowPostPaint += this.DataGridView_RowPostPaint;
            dataGridView1.KeyDown += DataGridView1_KeyDown;

            this.InitComboBoxForDataBase();
        }

        private void DataGridView1_KeyDown(object sender, KeyEventArgs e) {
            if(dataGridView1.SelectedRows.Count <= 0)
                return;
            var result = this.dataGridView1.SelectedRows.Cast<DataGridViewRow>().Select(d => d.DataBoundItem).Cast<TSideList>();
            foreach(var sideList in result)
                this.sideLists.Remove(sideList);

            this.dataGridView1.ClearDataSource();
            this.dataGridView1.DataSource = this.sideLists;
        }

        private void btnAddDetail_Click(object sender, EventArgs e) {
            if(string.IsNullOrEmpty(txbSysCode.Text)) {
                MessageBoxEx.Show("系统编号不能为空，请输入", "提示");
                return;
            }
            if(string.IsNullOrEmpty(txbTimeoutMinute.Text) || Convert.ToInt32(txbTimeoutMinute.Text) < 2) {
                MessageBoxEx.Show("超时时间不能为空，且不能小于2", "提示");
                return;
            }
            if(string.IsNullOrEmpty(txbAddress.Text)) {
                MessageBoxEx.Show("接口地址不能为空，请输入", "提示");
                return;
            }
            sideLists.Add(new TSideList {
                SysCode = this.txbSysCode.Text,
                TimeoutMinutes = Convert.ToInt32(this.txbTimeoutMinute.Text),
                Address = this.txbAddress.Text
            });
            this.dataGridView1.ClearDataSource();
            this.dataGridView1.DataSource = sideLists;
        }

        private void tsmiDelete_Click(object sender, EventArgs e) {
            if(dataGridView1.SelectedRows.Count <= 0)
                return;
            var result = this.dataGridView1.SelectedRows.Cast<DataGridViewRow>().Select(d => d.DataBoundItem).Cast<TSideList>();
            foreach(var sideList in result)
                this.sideLists.Remove(sideList);

            this.dataGridView1.ClearDataSource();
            this.dataGridView1.DataSource = this.sideLists;
        }

        private void InitComboBoxForDataBase() {
            var config = Utils.DeSerialize();
            if(config == null) {
                return;
            }
            using(var conn = new SQLiteConnection(string.Format($"Data Source={config.SqliteStoryPath};Version=3;"))) {
                conn.Open();
                var sqlExecute = "select Id,Name,ConnectString from ConnectStringConfigTb";
                var command = new SQLiteCommand(sqlExecute, conn);
                var reader = command.ExecuteReader();
                var source = new List<ConnectStringConfigTb>();
                while(reader.Read()) {
                    source.Add(new ConnectStringConfigTb {
                        Id = reader[0].ToString(),
                        Name = reader[1].ToString(),
                        ConnectString = reader[2].ToString()
                    });
                }

                //新增状态的接口配置，不允许编辑，必须在配置规则的情况下可以使用
                this.comboBoxDataBase.DataSource = null;
                this.comboBoxDataBase.DataSource = source;
                this.comboBoxDataBase.DisplayMember = "Name";
                this.comboBoxDataBase.ValueMember = "ConnectString";
            }
        }

        private void toolStripButton1_Click(object sender, EventArgs e) {
            if(string.IsNullOrEmpty(txbCode.Text)) {
                MessageBoxEx.Show("配置编号不能为空", "提示");
                return;
            }
            if(string.IsNullOrEmpty(txbName.Text)) {
                MessageBoxEx.Show("配置名称，请输入", "提示");
                return;
            }
            if(!sideLists.Any()) {
                MessageBoxEx.Show("调度地址清单不能为空", "提示");
                return;
            }
            if(this.comboBoxDataBase.SelectedItem == null) {
                MessageBoxEx.Show("数据库名称不能为空，请选择", "提示");
                return;
            }
            var db = this.comboBoxDataBase.SelectedItem as ConnectStringConfigTb;
            if(db == null)
                return;
            //https://www.cnblogs.com/ryanding/archive/2010/12/02/1892746.html
            using(var context = new MonitorSettingDataContext(db.ConnectString)) {
                try {
                    var tside = new TSide();
                    tside.Code = this.txbCode.Text;
                    tside.Name = this.txbName.Text;

                    context.TSide.InsertOnSubmit(tside);
                    sideLists.ForEach(d => d.TSide = tside);
                    context.TSideList.InsertAllOnSubmit(this.sideLists);
                    context.SubmitChanges();

                    //成功后，可以选择退出或者继续添加
                    this.sideLists.Clear();
                    this.txbCode.Text = string.Empty;
                    this.txbName.Text = string.Empty;
                    this.txbAddress.Text = string.Empty;
                    this.txbSysCode.Text = string.Empty;
                    this.txbTimeoutMinute.Text = string.Empty;

                    this.dataGridView1.DataSource = null;
                    var result = MessageBoxEx.Show("是否继续添加？", "询问", MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk);
                    if(result != DialogResult.OK) {
                        this.RasieEditSubmitted();
                    }
                } catch(Exception ex) {
                    MessageBoxEx.Show(this, ex.Message, "提示");
                }

            }
        }
    }
}
